package com.system.connect.springboot_flowers.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.system.connect.springboot_flowers.dto.FormDto;
import com.system.connect.springboot_flowers.dto.PostsFormDto;
import com.system.connect.springboot_flowers.entity.Originalposts;
import com.system.connect.springboot_flowers.entity.PostMetrics;
import com.system.connect.springboot_flowers.service.IOriginalpostsService;
import com.system.connect.springboot_flowers.service.IPostMetricsService;
import com.system.connect.springboot_flowers.service.IUsersService;
import com.system.connect.springboot_flowers.utils.R;
import com.system.connect.springboot_flowers.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 原创帖子表 前端控制器
 * </p>
 *
 * @author yang
 * @since 2025-01-16
 */
@RestController
@RequestMapping("/api/originalposts")
public class OriginalpostsController {

    @Autowired
    private IOriginalpostsService originalpostsService;

    @Autowired
    private IUsersService userService;

    @Autowired
    private IPostMetricsService iPostMetricsService;

    /**
     * 新建原创帖子
     */
    @PostMapping("/create")
    @Transactional
    public R create(@RequestBody FormDto formDto) {
        try {
            // 打印接收到的数据
            System.out.println("Received form data: " + formDto);
            
            // 详细打印每个字段的值
            System.out.println("anonymity: " + formDto.getAnonymity());
            System.out.println("category: " + formDto.getCategory());
            System.out.println("range: " + formDto.getRange());
            System.out.println("type: " + formDto.getType());
            System.out.println("mainboby: " + formDto.getMainboby());
            System.out.println("title: " + formDto.getTitle());
            
            // 验证必要字段
            if (formDto.getTitle() == null || formDto.getTitle().trim().isEmpty()) {
                return R.error("标题不能为空");
            }
            if (formDto.getMainboby() == null || formDto.getMainboby().trim().isEmpty()) {
                return R.error("内容不能为空");
            }
            if (formDto.getCategory() == null || formDto.getCategory().trim().isEmpty()) {
                return R.error("分类不能为空");
            }
            
            System.out.println("开始创建帖子...");
            // 创建帖子
            Originalposts originalpost = new Originalposts();
            originalpost.setUserId(Integer.valueOf(TokenUtils.getUser()));
            originalpost.setTiele(formDto.getTitle());
            originalpost.setContent(formDto.getMainboby());
            originalpost.setCategory(formDto.getCategory());
            originalpost.setType(formDto.getType());
            originalpost.setAnonymity(formDto.getAnonymity());
            originalpost.setIsDelete(false);
            originalpost.setCreatedAt(LocalDateTime.now());  // 设置创建时间
            
            boolean result = originalpostsService.save(originalpost);
            System.out.println("创建帖子结果: " + result);
            
            if (result) {
                // 创建成功后，初始化帖子指标
                try {
                    // 使用最新插入的帖子ID
                    PostMetrics metrics = new PostMetrics();
                    metrics.setPostId(originalpost.getOriginalpostid());  // 使用自动生成的ID
                    metrics.setViews(0);
                    metrics.setLikes(0);
                    metrics.setReplies(0);
                    metrics.setFavorites(0);
                    iPostMetricsService.save(metrics);
                    System.out.println("帖子指标初始化成功");
                } catch (Exception e) {
                    System.out.println("初始化帖子指标失败: " + e.getMessage());
                    e.printStackTrace();
                }
                
                return R.success("新建原创帖子成功");
            } else {
                return R.error("新建原创帖子失败，请检查数据格式");
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("创建帖子异常: " + e.getMessage());
            return R.error("新建原创帖子失败：" + e.getMessage());
        }
    }

    /**
     * 获取帖子列表
     */
    @GetMapping("/list")
    public R list() {

        ArrayList<Originalposts> originalposts = (ArrayList<Originalposts>)originalpostsService.list();
        ArrayList<PostMetrics> postMetrics = (ArrayList<PostMetrics>)iPostMetricsService.list();
        ArrayList<PostsFormDto> postsFormDtos = new ArrayList<>();


        for (Originalposts originalpost : originalposts){
            PostsFormDto postsFormDto = new PostsFormDto();
            postsFormDto.setPost_id(originalpost.getOriginalpostid());
            postsFormDto.setType(originalpost.getType());
            postsFormDto.setCategory(originalpost.getCategory());
            postsFormDto.setMainboby(originalpost.getContent());
            postsFormDto.setTitle(originalpost.getTiele());
            postsFormDto.setCreatedAt(originalpost.getCreatedAt().toString());
            postsFormDto.setUser_avatar(userService.getById(originalpost.getUserId()).getAvatarUrl());
            postsFormDto.setUser_nickname(userService.getById(originalpost.getUserId()).getUsername());

            for (PostMetrics postMetric : postMetrics){
                if (postMetric.getPostId().equals(originalpost.getOriginalpostid())){
                    postsFormDto.setReplies(postMetric.getReplies());
                    postsFormDto.setFavorites(postMetric.getFavorites());
                    postsFormDto.setLikes(postMetric.getLikes());
                    postsFormDto.setViews(postMetric.getViews());
                }
            }
            postsFormDtos.add(postsFormDto);
        }
        System.out.println("postsFormDtos==>"+postsFormDtos);
        return R.success(postsFormDtos);
    }

    /**
     * 获取帖子详情
     */
    @GetMapping("/{post_id}") // 确保路径与前端请求匹配
    public R getPostDetail(@PathVariable("post_id") Integer postId) {
        //游览量增加
        QueryWrapper<PostMetrics> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("id", "post_id", "views", "replies", "favorites") // 移除了 'likes'
                .eq("post_id", postId);
        PostMetrics postMetrics = iPostMetricsService.getOne(queryWrapper);

        if (postMetrics != null) {
            // 如果找到了记录，则增加查看次数
            postMetrics.setViews(postMetrics.getViews() + 1);
            iPostMetricsService.updateById(postMetrics); // 更新数据库中的记录
        } else {
            // 如果没有找到记录，则创建一个新的 PostMetrics 实例
            postMetrics = new PostMetrics();
            postMetrics.setPostId(postId); // 设置 postId
            postMetrics.setViews(1); // 初始化查看次数为1
            postMetrics.setReplies(0); // 可选：初始化其他字段
            postMetrics.setFavorites(0); // 可选：初始化其他字段

            iPostMetricsService.save(postMetrics); // 保存新的记录到数据库
        }

        // 直接通过服务层的方法获取指定ID的帖子信息
        System.out.println("postId==>"+postId);
        Originalposts post = originalpostsService.getById(postId);
        PostsFormDto postsFormDto = new PostsFormDto();
        postsFormDto.setPost_id(post.getOriginalpostid());
        postsFormDto.setType(post.getType());
        postsFormDto.setCategory(post.getCategory());
        postsFormDto.setMainboby(post.getContent());
        postsFormDto.setTitle(post.getTiele());
        postsFormDto.setCreatedAt(post.getCreatedAt().toString());
        postsFormDto.setUser_avatar(userService.getById(post.getUserId()).getAvatarUrl());
        postsFormDto.setUser_nickname(userService.getById(post.getUserId()).getUsername());
        postsFormDto.setReplies(postMetrics.getReplies());
        postsFormDto.setFavorites(postMetrics.getFavorites());
        postsFormDto.setLikes(postMetrics.getLikes());
        postsFormDto.setViews(postMetrics.getViews());

        if (post == null) {
            return R.error("帖子不存在");
        }

        return R.success(postsFormDto);
    }

    /**
     * 管理员获取所有帖子列表
     */
    @GetMapping("/admin/list")
    public R adminGetAllPosts(
            @RequestParam(required = false) String category,
            @RequestParam(required = false) String type,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size) {
        try {
            QueryWrapper<Originalposts> queryWrapper = new QueryWrapper<>();
            
            // 添加筛选条件
            if (category != null && !category.isEmpty()) {
                queryWrapper.eq("category", category);
            }
            if (type != null && !type.isEmpty()) {
                queryWrapper.eq("type", type);
            }
            
            // 按创建时间倒序排序
            queryWrapper.orderByDesc("created_at");
            
            // 获取帖子列表
            List<Originalposts> originalposts = originalpostsService.list(queryWrapper);
            List<PostsFormDto> postsFormDtos = new ArrayList<>();
            
            // 转换为前端需要的格式
            for (Originalposts post : originalposts) {
                PostsFormDto dto = new PostsFormDto();
                dto.setPost_id(post.getOriginalpostid());
                dto.setType(post.getType());
                dto.setCategory(post.getCategory());
                dto.setMainboby(post.getContent());
                dto.setTitle(post.getTiele());
                dto.setCreatedAt(post.getCreatedAt().toString());
                dto.setUser_avatar(userService.getById(post.getUserId()).getAvatarUrl());
                dto.setUser_nickname(userService.getById(post.getUserId()).getUsername());
                
                // 获取帖子指标
                PostMetrics metrics = iPostMetricsService.getByPostId(post.getOriginalpostid());
                if (metrics != null) {
                    dto.setReplies(metrics.getReplies());
                    dto.setFavorites(metrics.getFavorites());
                    dto.setLikes(metrics.getLikes());
                    dto.setViews(metrics.getViews());
                }
                
                postsFormDtos.add(dto);
            }
            
            Map<String, Object> result = new HashMap<>();
            result.put("posts", postsFormDtos);
            result.put("total", originalpostsService.count(queryWrapper));
            
            return R.success(result);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("获取帖子列表失败：" + e.getMessage());
        }
    }
    
    /**
     * 管理员删除帖子
     */
    @DeleteMapping("/admin/delete/{id}")
    @Transactional
    public R adminDeletePost(@PathVariable("id") Integer postId) {
        try {
            // 先删除帖子指标
            QueryWrapper<PostMetrics> metricsWrapper = new QueryWrapper<>();
            metricsWrapper.eq("post_id", postId);
            iPostMetricsService.remove(metricsWrapper);
            
            // 再删除帖子
            boolean result = originalpostsService.removeById(postId);
            
            return result ? R.success("删除帖子成功") : R.error("删除帖子失败");
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("删除帖子失败：" + e.getMessage());
        }
    }
    
    /**
     * 管理员批量删除帖子
     */
    @DeleteMapping("/admin/batchDelete")
    @Transactional
    public R adminBatchDeletePosts(@RequestBody List<Integer> postIds) {
        try {
            // 批量删除帖子指标
            for (Integer postId : postIds) {
                QueryWrapper<PostMetrics> metricsWrapper = new QueryWrapper<>();
                metricsWrapper.eq("post_id", postId);
                iPostMetricsService.remove(metricsWrapper);
            }
            
            // 批量删除帖子
            boolean result = originalpostsService.removeByIds(postIds);
            
            return result ? R.success("批量删除帖子成功") : R.error("批量删除帖子失败");
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("批量删除帖子失败：" + e.getMessage());
        }
    }
    
    /**
     * 管理员修改帖子
     */
    @PutMapping("/admin/update/{id}")
    public R adminUpdatePost(@PathVariable("id") Integer postId, @RequestBody FormDto formDto) {
        try {
            Originalposts post = originalpostsService.getById(postId);
            if (post == null) {
                return R.error("帖子不存在");
            }
            
            // 更新帖子信息
            if (formDto.getTitle() != null) {
                post.setTiele(formDto.getTitle());
            }
            if (formDto.getMainboby() != null) {
                post.setContent(formDto.getMainboby());
            }
            if (formDto.getCategory() != null) {
                post.setCategory(formDto.getCategory());
            }
            if (formDto.getType() != null) {
                post.setType(formDto.getType());
            }
            
            boolean result = originalpostsService.updateById(post);
            
            return result ? R.success("更新帖子成功") : R.error("更新帖子失败");
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("更新帖子失败：" + e.getMessage());
        }
    }
    
    /**
     * 管理员设置帖子置顶或精华
     */
    @PutMapping("/admin/setFlag/{id}")
    public R adminSetPostFlag(
            @PathVariable("id") Integer postId, 
            @RequestParam(required = false) Boolean isTop,
            @RequestParam(required = false) Boolean isEssence) {
        try {
            Originalposts post = originalpostsService.getById(postId);
            if (post == null) {
                return R.error("帖子不存在");
            }
            
            // 这里假设Originalposts类中有isTop和isEssence字段
            // 如果没有，需要先修改实体类添加这些字段
            if (isTop != null) {
                // 设置置顶状态
                // post.setIsTop(isTop);
            }
            if (isEssence != null) {
                // 设置精华状态
                // post.setIsEssence(isEssence);
            }
            
            boolean result = originalpostsService.updateById(post);
            
            return result ? R.success("设置帖子标记成功") : R.error("设置帖子标记失败");
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("设置帖子标记失败：" + e.getMessage());
        }
    }
    
    /**
     * 管理员获取帖子统计信息
     */
    @GetMapping("/admin/statistics")
    public R adminGetPostStatistics() {
        try {
            Map<String, Object> statistics = new HashMap<>();
            
            // 获取总帖子数
            int totalPosts = originalpostsService.count();
            statistics.put("totalPosts", totalPosts);
            
            // 获取各分类帖子数量
            List<Map<String, Object>> categoryCounts = originalpostsService.getCategoryCount();
            statistics.put("categoryCounts", categoryCounts);
            
            // 获取今日新增帖子数
            LocalDateTime today = LocalDateTime.now().withHour(0).withMinute(0).withSecond(0).withNano(0);
            QueryWrapper<Originalposts> todayWrapper = new QueryWrapper<>();
            todayWrapper.ge("created_at", today);
            int todayPosts = originalpostsService.count(todayWrapper);
            statistics.put("todayPosts", todayPosts);
            
            return R.success(statistics);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("获取帖子统计信息失败：" + e.getMessage());
        }
    }
}

